<template>
  <div>
    <el-dialog
      :title="title"
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
      custom-class="dialog-my"
    >
      <el-form :model="form" ref="myform" :rules="rules" label-width="120px">
        <el-form-item label="定价方案名称" prop="regulationName">
          <el-input
            v-model="form.regulationName"
            style="width: 244px"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="场区" prop="regionId">
          <el-select
            v-model="form.regionId"
            clearable
            placeholder="请选择"
            @change="getRegionData"
          >
            <el-option
              v-for="item in regionList"
              :key="item.id"
              :label="item.regionName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="addDate"
          style="margin-left: 120px"
          >新增时段</el-button
        >
        <el-row v-for="(item, index) in form.regulationDetailList" :key="index">
          <el-col :span="24">
            <div class="title">
              <h3>时段{{ index + 1 }}</h3>
              <p style="margin-right: 40px">时间(24时制)</p>
              <el-button
                v-if="index > 0"
                type="danger"
                @click="del(index)"
                icon="el-icon-delete"
                circle
              ></el-button>
            </div>
          </el-col>
          <el-col :span="8">
            <el-form-item
              :prop="'regulationDetailList.' + index + '.startTime'"
              :rules="rules.startTime"
              label-width="30px"
            >
              <el-time-select
                placeholder="起始时间"
                v-model="item.startTime"
                :disabled="!form.regionId"
                :picker-options="{
                  start: '00:00',
                  step: region.interval == 1 ? '00:60' : '00:30',
                  end: '24:00',
                  minTime: setMinTime(index),
                  maxTime: region.endTime,
                }"
              >
              </el-time-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              :prop="`regulationDetailList[${index}].endTime`"
              :rules="rules.endTime"
              label-width="30px"
            >
              <el-time-select
                :disabled="!form.regionId"
                placeholder="结束时间"
                v-model="item.endTime"
                :picker-options="{
                  start: '00:00',
                  step: region.interval == 1 ? '00:60' : '00:30',
                  end: '24:00',
                  minTime: item.startTime,
                  maxTime: region.endTime,
                }"
              >
              </el-time-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              :prop="'regulationDetailList.' + index + '.price'"
              :rules="rules.price"
              label-width="30px"
            >
              <el-input
                v-model="item.price"
                :disabled="!form.regionId"
                style="width: 244px"
                placeholder="场次价格（元）"
              ></el-input>
            </el-form-item>
          </el-col>
          <div
            v-for="(dt, x) in item.cutPriceList"
            :key="x"
            style="width: 100%; overflow: hidden"
          >
            <el-col :span="8">
              <el-form-item label-width="30px">
                <el-select
                  v-model="dt.levelId"
                  :disabled="!form.regionId"
                  placeholder="请选择会员等级"
                >
                  <el-option
                    v-for="item in cardLevelList"
                    :key="item.levelId"
                    :label="item.levelName"
                    :value="item.levelId"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item
                label-width="30px"
                :prop="`regulationDetailList[${index}].cutPriceList[${x}].cutPrice`"
              >
                <el-input
                  v-model="dt.cutPrice"
                  :disabled="!form.regionId"
                  style="width: 244px"
                  placeholder="请输入会员价格"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <i
                class="el-icon-delete"
                style="
                  cursor: pointer;
                  font-size: 24px;
                  margin-top: 8px;
                  margin-left: 30px;
                "
                v-if="x > 0"
                @click="delLevel(index, x)"
              ></i>
              <i
                class="el-icon-plus"
                style="
                  cursor: pointer;
                  font-size: 24px;
                  margin-top: 8px;
                  margin-left: 30px;
                "
                @click="addLevel(index)"
                v-if="x == 0"
              ></i>
            </el-col>
          </div>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { regionPageList, regulationSave, cardLevelPageList } from "@/config/api"
import { times, divide } from "@/utils/tools"
export default {
  data () {
    return {
      dialogFormVisible: false,
      title: '',
      regionList: [],
      region: {},
      cardLevelList: [],
      form: {
        regulationName: undefined,
        regionId: undefined,
        regulationDetailList: [
          {
            startTime: "",
            endTime: "",
            price: "",
            cutPriceList: [
              {
                levelId: '',
                cutPrice: ''
              }
            ],
          }
        ]
      },
      rules: {
        regulationName: [
          { required: true, message: '请输入定价方案名称', trigger: 'blur' }],
        regionId: [
          { required: true, message: '请选择场区', trigger: 'change' }],
        itemId: [
          { required: true, message: '请选择项目', trigger: 'change' }
        ],
        startTime: [
          { required: true, message: '请选择开始时间', trigger: 'change' }
        ],
        endTime: [
          { required: true, message: '请选择结束时间', trigger: 'change' }
        ],
        price: [
          { required: true, message: '请输入场次价格', trigger: 'blur' }
        ],
        levelId: [
          { required: true, message: '请选择会员等级', trigger: 'change' }
        ],
        cutPrice: [
          { required: true, message: '请输入会员价格', trigger: 'change' }
        ]
      }

    }
  },
  methods: {
    addShow () {
      this.title = '新增'
      this.getRegionList()
      this.resetFields()
      this.getLevelList()
      this.dialogFormVisible = true
    },
    editShow (e) {
      let recore = JSON.parse(JSON.stringify(e))
      this.title = '编辑'
      recore.regulationDetailList.map(item => {
        item.price = divide(item.price, 100)
        item.cutPriceList.map(it => {
          it.cutPrice = divide(it.cutPrice, 100)
        })
      })
      this.getRegionList()
      this.getLevelList()
      this.resetFields()
      this.form = {
        id: recore.id,
        regulationName: recore.regulationName,
        regionId: recore.regionId,
        regulationDetailList: recore.regulationDetailList
      }
      this.dialogFormVisible = true
    },
    getRegionList () {
      regionPageList().then(res => {
        this.regionList = res.data.result.list
      })
    },
    getLevelList () {
      cardLevelPageList().then(res => {
        this.cardLevelList = res.data.result.list
      })
    },
    addDate () {
      let state = true
      this.form.regulationDetailList.map(item => {
        if (!item.startTime || !item.endTime || !item.price) {
          state = false

        }
      })
      if (!this.form.regionId) {
        this.$confirm('请选择场区, 才能新增时段?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        return false
      }
      if (!state) {
        this.$confirm('请将现有的时段填写完成, 才能新增时段?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        return false
      }
      this.form.regulationDetailList.push({
        startTime: "",
        endTime: "",
        price: "",
        cutPriceList: [
          {
            levelId: '',
            cutPrice: ''
          }
        ],
      })
    },
    del (index) {
      this.$confirm('此操作将进行删除时段, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.form.regulationDetailList.splice(index, 1)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    setMinTime (index) {
      if (index == 0) {
        return this.region.startTime
      } else {
        let endTime = this.form.regulationDetailList[index - 1].endTime
        let startTime = this.form.regulationDetailList[index - 1].startTime
        let res = this.setTimeForMat(endTime, startTime)
        return res.start
      }
    },

    setTimeForMat (start, end) {
      let s = new Date("2022-11-11 " + start)
      let d = new Date("2022-11-11 " + end)
      let s1 = "", s2 = "";
      if (this.region.interval == 1) {
        s1 = s.valueOf() - 60 * 60 * 1000
        s2 = d.valueOf() + 60 * 60 * 1000
      } else {
        s1 = s.valueOf() - 30 * 60 * 1000
        s2 = d.valueOf() + 30 * 60 * 1000
      }
      function r (n) {
        return n > 9 ? n : '0' + n
      }
      return { start: r(new Date(s1).getHours()) + ':' + r(new Date(s1).getMinutes()), end: r(new Date(s2).getHours()) + ':' + r(new Date(s2).getMinutes()) }
    },
    getRegionData (e) {
      this.regionList.map(item => {
        if (item.id == e) {
          this.region = item
        }
      })
      let res = this.setTimeForMat(this.region.businessStartTime, this.region.businessEndTime)
      this.region.startTime = res.start
      this.region.endTime = res.end

    },
    addLevel (i) {
      this.form.regulationDetailList[i].cutPriceList.push({
        levelId: '',
        cutPrice: ''
      })
    },
    delLevel (i, x) {
      this.form.regulationDetailList[i].cutPriceList.splice(x, 1)
    },
    resetFields () {
      this.form = {
        regulationName: undefined,
        regionId: undefined,
        regulationDetailList: [
          {
            startTime: "",
            endTime: "",
            price: "",
            cutPriceList: [
              {
                levelId: '',
                cutPrice: ''
              }
            ],
          }
        ]
      }
    },
    submit () {
      let state = false
      let state2 = false
      console.log(this.form)
      this.form.regulationDetailList.map(item => {
        if (item.price < 1) {
          state = true
        }
        item.cutPriceList.map(i => {
          if (i.levelId === '' || i.cutPrice === '') {
            state2 = true
          }
        })
      })

      if (state) {
        this.$confirm('场次价格不能小于1元?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        return false
      }
      if (state2) {
        this.$confirm('请输入会员等级或会员价格', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        return false
      }
      this.$refs['myform'].validate((valid) => {
        if (valid) {
          let params = JSON.parse(JSON.stringify(this.form))
          params.regulationDetailList.map(item => {
            item.price = times(item.price, 100)
            item.cutPriceList.map(it => {
              it.cutPrice = times(it.cutPrice, 100)
            })
          })
          regulationSave(params).then(res => {
            console.log(res.data.status)
            if (res.data.status == 200) {
              this.dialogFormVisible = false
              this.$parent.getData()
              this.$message({
                message: '操作成功',
                type: 'success'
              });
            }
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });

    }
  }
}
</script>
<style lang="scss" scoped>
.title {
  display: flex;
  align-items: center;
  margin-left: 120px;
  h3 {
    margin-right: 10px;
  }
}
</style>